package com.beauty.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.ImageView;

/**
 * 异步加载图片
 */
public class AsyncImageLoad extends AsyncTask<String, Integer, Uri> {
	private ImageView imageView;
	private static File file;
	private Context context;

	public AsyncImageLoad(Context context, ImageView imageView, String path) {

		if (file == null) {
			file = new File(Environment.getExternalStorageDirectory(),"Beauty");	
		}
		if (!file.exists())
			file.mkdirs();
		this.imageView = imageView;
		this.context = context;
		this.execute(path);
	}

	protected Uri doInBackground(String... params) {// 子线程中执行的
		try {
			return getImage(params[0], file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	protected void onPostExecute(Uri result) {// 运行在主线程
		if (result != null && imageView != null){
			try {
				Bitmap bitmap = BitmapFactory.decodeStream(context
						.getContentResolver().openInputStream(result));
				imageView.setImageBitmap(bitmap);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获取网络图片,如果图片存在于缓存中，就返回该图片，否则从网络中加载该图片并缓存起来
	 * 
	 * @param path
	 *            图片路径
	 * @return
	 */
	public static Uri getImage(String path, File cacheDir) throws Exception {
		File localFile = new File(cacheDir, getMD5(path)
				+ path.substring(path.lastIndexOf(".")));
		if (localFile.exists()) {
			return Uri.fromFile(localFile);
		} else {
			HttpURLConnection conn = (HttpURLConnection) new URL(path)
					.openConnection();
			conn.setConnectTimeout(5000);
			conn.setRequestMethod("GET");
			if (conn.getResponseCode() == 200) {
				FileOutputStream outStream = new FileOutputStream(localFile);
				InputStream inputStream = conn.getInputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = inputStream.read(buffer)) != -1) {
					outStream.write(buffer, 0, len);
				}
				inputStream.close();
				outStream.close();
				return Uri.fromFile(localFile);
			}
		}
		return null;
	}
	
	public static String getMD5(String content) {
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			digest.update(content.getBytes());
			return getHashString(digest);
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
	
    private static String getHashString(MessageDigest digest) {
        StringBuilder builder = new StringBuilder();
        for (byte b : digest.digest()) {
            builder.append(Integer.toHexString((b >> 4) & 0xf));
            builder.append(Integer.toHexString(b & 0xf));
        }
        return builder.toString();
    }
}
